package com.share.drools.hello;

import lombok.Data;
import lombok.NoArgsConstructor;
import org.drools.core.event.DebugAgendaEventListener;
import org.drools.core.event.DebugRuleRuntimeEventListener;
import org.kie.api.KieServices;
import org.kie.api.logger.KieRuntimeLogger;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;

import java.util.ArrayList;
import java.util.List;

/**
 * @author caifan
 * @created 2021/4/2
 * description:
 */
public class HelloWorldDrools {

    public static void main(String[] args) {
        KieServices kieServices = KieServices.get();
        KieContainer kieContainer = kieServices.getKieClasspathContainer();
        execute(kieServices, kieContainer);

    }

    public static void execute(KieServices ks, KieContainer kc) {
        // 从META-INF/kmodule.xml读取配置
        KieSession kieSession = kc.newKieSession("HelloWorldKS");

        // 读取helloworld.drl
        kieSession.setGlobal("list", new ArrayList<Object>());

        // 添加监听器
        kieSession.addEventListener(new DebugAgendaEventListener());
        kieSession.addEventListener(new DebugRuleRuntimeEventListener());

        // 添加日志文件
        KieRuntimeLogger runtimeLogger = ks.getLoggers().newFileLogger(kieSession, "./helloworld");
        // 线程文件
//        KieRuntimeLogger kieRuntimeLogger = ks.getLoggers().newThreadedFileLogger(kieSession, "./hellowold", 1000);

        // session
        final Message message = new Message();
        message.setMessage("hello world");
        message.setStatus(Message.HELLO);
        kieSession.insert(message);

        kieSession.fireAllRules();

        runtimeLogger.close();
        kieSession.dispose();
    }

    @Data
    @NoArgsConstructor
    public static class Message {
        public static final int HELLO   = 0;
        public static final int GOODBYE = 1;

        private String message;

        private int status;

        public static Message doSomething(Message message) {
            return message;
        }

        public boolean isSomething(String msg, List<Object> list) {
            list.add(this);
            return this.message.equals(msg);
        }
    }
}
